import XtxInfiniteLoading from "@/components/library/xtxIinfiniteIloading";
import GoodsItems from "../TopCategory/components/goodsItem";
import SubBread from "./components/subBread";
import SubFilter from "./components/subFilter";
import SubSort from "./components/subSort";
import "./index.scss";
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { useAxiosWithAuth } from "@/utils/useAxiosWidthAuth";
function subCategory() {
  const [loading, setLoading] = useState(false);
  const [finished, setFinished] = useState(false);
  const [goodsList, setGoodsList] = useState<any>([]);
  const { id } = useParams();
  const [params, setParams] = useState<{
    page: number;
    pageSize: number;
    categoryId: string;
  }>({
    page: 1,
    pageSize: 20,
    categoryId: id || "",
  });

  const axios = useAxiosWithAuth();
  const findSubCategoryGoods = async () => {
    try {
      const res: any = await axios({
        method: "post",
        url: "/category/goods/temporary",
        data: params,
      });

      if (res?.result?.items.length) {
        setGoodsList((prevGoodsList: any) => [
          ...prevGoodsList,
          ...res.result.items,
        ]);
        // 数据成功加载后递增 page
        setParams((prevParams) => ({
          ...prevParams,
          page: prevParams.page + 1,
        }));
      } else {
        setFinished(true); // 没有更多数据时设置 finished 为 true
      }
    } finally {
      setLoading(false); // 请求完成后将 loading 设置为 false
    }
  };
  useEffect(() => {
    findSubCategoryGoods();
  }, [loading, finished]);
  // 当 id 变化时，重置分页和数据
  useEffect(() => {
    setGoodsList([]); // 清空商品列表
    setParams({
      ...params,
      page: 1,
    });
    setFinished(false); // 重置 finished 状态
  }, [id]); // id 变化时触发
  const getData = function () {
    setLoading(true);
  };
  const sortChange = function (playload: any) {
    setGoodsList([]); // 清空商品列表
    setParams({ ...params, page: 1, ...playload });
    setFinished(false); // 重置 finished 状态
  };
  const filterChange = function (playload: any) {
    setGoodsList([]); // 清空商品列表
    setParams({ ...params, page: 1, ...playload });
    setFinished(false); // 重置 finished 状态
  };
  return (
    <div className="sub-category">
      <div className="container">
        <SubBread></SubBread>
        <SubFilter filterChange={filterChange}></SubFilter>
        <div className="goods-list">
          <SubSort sortChange={sortChange} />
          <ul>
            {goodsList &&
              goodsList.map((item: any) => (
                <li key={item.id}>
                  <GoodsItems goods={item} />
                </li>
              ))}
          </ul>
          <XtxInfiniteLoading
            loading={loading}
            finished={finished}
            infinit={getData}
          ></XtxInfiniteLoading>
        </div>
      </div>
    </div>
  );
}

export default subCategory;
